# coding=utf-8
import arcpy
from arcpy.sa import *
from Common import get_temp_shp_path, get_temp_dbf_path,get_temp_raster_path
import os
import time


def select_from_shp(shp_path, exp):
    # shp数据筛选
    print ("shp执行开始")
    if os.path.isfile(shp_path):
        print "文件存在"

    out_path = get_temp_shp_path(shp_path)
    print (shp_path, out_path, exp)
    arcpy.Select_analysis(shp_path, out_path, exp)
    # arcpy.TableSelect_analysis(shp_path, out_path, exp)

    print ("筛选")
    return out_path


def add_field(shp_path, name, field_type):
    # 添加字段
    temp = copy_shp(shp_path)
    print (temp, name, field_type)
    time.sleep(2)
    arcpy.AddField_management(temp, name, field_type)
    print ("添加字段")
    return temp


def copy_shp(shp_path):
    # 复制shp
    out_path = get_temp_shp_path(shp_path)
    feature_set = arcpy.FeatureSet()
    feature_set.load(shp_path)
    feature_set.save(out_path)
    print ("复制数据")
    return out_path


def calculate_field(shp_path, field_name, expression_str, expression_type="PYTHON_9.3"):
    # 复制shp
    out_path = shp_path
    arcpy.CalculateField_management(shp_path, field_name, expression_str, expression_type)
    print ("计算字段")
    return out_path


def statistics_analysis(in_table, statistics_field, statistics_type, group_by=None):
    # 汇总统计
    out_table = get_temp_dbf_path(in_table)
    arcpy.Statistics_analysis(in_table, out_table, [[statistics_field, statistics_type]], group_by)
    return out_table


def cut_raster(raster, in_mask_data):
    # 掩膜提取
    out_raster = get_temp_raster_path(raster)
    outExtractByMask = ExtractByMask(raster, in_mask_data)
    outExtractByMask.save(out_raster)
    return out_raster
